package net.sf.midollo.net.io;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLConnection;

import net.sf.midollo.io.IOStream;
import net.sf.midollo.io.IOUtils;

public class URLIOStream implements IOStream {

  protected final URLConnection urlConnection;
  protected boolean connected;

  public URLIOStream(URLConnection urlConnection) throws IOException {
    this.urlConnection = urlConnection;
    this.connected = false;
  }

  public URLConnection getURLConnection() {
    return this.urlConnection;
  }

  public InputStream getInput() throws IOException {
    if (this.urlConnection.getDoInput()) {
      connect();
      return this.urlConnection.getInputStream();
    }
    return IOUtils.NULL_INPUT;
  }

  public OutputStream getOutput() throws IOException {
    if (this.urlConnection.getDoOutput()) {
      connect();
      return this.urlConnection.getOutputStream();
    }
    return IOUtils.NULL_OUTPUT;
  }

  public synchronized void close() throws IOException {
    this.connected = false;
  }

  protected synchronized void connect() throws IOException {
    if (!this.connected) {
      this.urlConnection.connect();
      this.connected = true;
    }
  }
}
